package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.common.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    //minio
    private final FileStorageService fileStorageService;

    private final WmMaterialMapper wmMaterialMapper;
    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minio中


        //2.1拼接文件名称
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //aa.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片到minio中 ：{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("上传文件失败");
        }

        //3.保存到数据库中

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //4.返回结果


        return ResponseResult.okResult(wmMaterial);
    }


    /**
     * 素材查看
     *
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto wmMaterialDto) {

        //1.检查分页参数
        wmMaterialDto.checkParam();

        //2.分页查询
        IPage page = new Page(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaqueryWrapper = new LambdaQueryWrapper<>();
        //是否收藏
        if (wmMaterialDto.getIsCollection() != null && wmMaterialDto.getIsCollection() == 1){
            lambdaqueryWrapper.eq(WmMaterial::getIsCollection, wmMaterialDto.getIsCollection());
        }


        //按照用户查询
        lambdaqueryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());

        //按照时间倒叙
        lambdaqueryWrapper.orderByDesc(WmMaterial::getCreatedTime);


        page = page(page, lambdaqueryWrapper);


        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 图片删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional//保证数据一致性
    public ResponseResult deleteImageById(Integer id) {


        //1.检查id是否存在
        if (id == null || id <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.检查数据是否存在
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }


        //3.0 删除图片在minio中
        try {
            fileStorageService.delete(wmMaterial.getUrl());
        } catch (Exception e) {
            log.error("在minio中删除图片失败...");
            throw new RuntimeException(e);

        }


        //3.1 数据库删除图片
        int delete = wmMaterialMapper.deleteById(id);
        if (delete == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"图片删除失败");
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 收藏图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectById(Integer id) {

        //1.判断id是否为空
        if (id == null || id <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断图片是否存在
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"图片不存在");
        }

        WmMaterial wmMaterial1 = new WmMaterial();
        wmMaterial1.setId(id);
        wmMaterial1.setIsCollection((short) 1);

        //收藏图片
        wmMaterialMapper.updateById(wmMaterial1);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 取消收藏图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollectById(Integer id) {
        //1.判断id是否为空
        if (id == null || id <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断图片是否存在
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"图片不存在");
        }

        WmMaterial wmMaterial1 = new WmMaterial();
        wmMaterial1.setId(id);
        wmMaterial1.setIsCollection((short) 0);

        //取消收藏图片
        wmMaterialMapper.updateById(wmMaterial1);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}





















